<template>
  <view class="pt4 px-2 publish h-full">
    <wd-message-box />
    <wd-toast />
    <view class="form">
      <form @submit="formSubmit">
        <wd-cell-group custom-class="group" title="基础信息" border>
          <wd-calendar v-model="formData.COL_0.value" label="提油日期" />
          <wd-picker required :columns="columns" label="项目名称" value-key="COL_4" label-key="COL_3" v-model="formData.COL_20.value" />
          <wd-picker
            :disabled="!formData.COL_20.value"
            required
            :columns="kehuList"
            label-key="label"
            value-key="value"
            label="采购单"
            v-model="formData.COL_4.value"
          />
          <wd-input type="digit" label="提油数量" placeholder="请输入提油" required v-model="formData.COL_6.value" />
        </wd-cell-group>
        <wd-cell title="提油单位" title-width="90px" required>
          <wd-radio-group v-model="formData.unit_type.value" size="small" shape="button" inline>
            <wd-radio value="吨">吨</wd-radio>
            <wd-radio value="升">升</wd-radio>
          </wd-radio-group>
        </wd-cell>
        <wd-cell title="车牌输入" :value="formData.COL_14.value || '点击输入'" clickable @click="chooseLicensePlate" />
        <view class="h-10"></view>
        <wd-cell-group title="票据上传" border class="p3">
          <view class="h-10"></view>
          <wd-upload
            multiple
            :file-list="fileList"
            action="https://miniappnew.zhangmushiye.com/api/file/uploadFile/record"
            :header="{
              'Blade-Auth': token
            }"
            @change="handleChange"
          ></wd-upload>
        </wd-cell-group>
        <!--        密度：{{ formData.other.COL_6 }} 吨数：{{ total.ton }} 单价：{{ formData.other.COL_7 }} 金额：{{ total.price }}-->
        <view class="text-center p3">
          <wd-button block type="success" @click="formSubmit">提交</wd-button>
        </view>
      </form>
    </view>
  </view>
</template>

<script setup>
import dayjs from 'dayjs'

const { userInfo } = storeToRefs(useAuthStore())

import { useMessage } from 'wot-design-uni'
import { useToast } from 'wot-design-uni'

const toast = useToast()
const messageBox = useMessage()
import { ref } from 'vue'

const formData = ref({
  COL_0: {
    field: 'COL_0',
    fieldId: 565,
    fieldName: '提油日期',
    dataType: 'DATETIME',
    tableAliasName: 'uKXdX',
    tableName: 'ODS_Pickup',
    value: dayjs().format('YYYY-MM-DD')
  },
  COL_1: {
    field: 'COL_1',
    fieldId: 566,
    fieldName: '项目名称',
    dataType: 'STRING',
    tableAliasName: 'uKXdX',
    tableName: 'ODS_Pickup',
    value: ''
  },
  COL_2: {
    field: 'COL_2',
    fieldId: 567,
    fieldName: '油品名称',
    dataType: 'STRING',
    tableAliasName: 'uKXdX',
    tableName: 'ODS_Pickup',
    value: ''
  },
  COL_3: {
    field: 'COL_3',
    fieldId: 568,
    fieldName: '油品型号',
    dataType: 'STRING',
    tableAliasName: 'uKXdX',
    tableName: 'ODS_Pickup',
    value: ''
  },
  COL_4: {
    field: 'COL_4',
    fieldId: 569,
    fieldName: '采购单号',
    dataType: 'STRING',
    tableAliasName: 'uKXdX',
    tableName: 'ODS_Pickup',
    value: ''
  },
  COL_5: {
    field: 'COL_5',
    fieldId: 570,
    fieldName: '打款数量（吨）',
    dataType: 'NUMBER',
    tableAliasName: 'uKXdX',
    tableName: 'ODS_Pickup',
    value: ''
  },
  COL_6: {
    field: 'COL_6',
    fieldId: 571,
    fieldName: '实际提油',
    dataType: 'NUMBER',
    tableAliasName: 'uKXdX',
    tableName: 'ODS_Pickup',
    value: ''
  },
  COL_7: {
    field: 'COL_7',
    fieldId: 572,
    fieldName: '单价',
    dataType: 'NUMBER',
    tableAliasName: 'uKXdX',
    tableName: 'ODS_Pickup',
    value: ''
  },
  COL_8: {
    field: 'COL_8',
    fieldId: 573,
    fieldName: '金额',
    dataType: 'NUMBER',
    tableAliasName: 'uKXdX',
    tableName: 'ODS_Pickup',
    value: ''
  },
  COL_9: {
    field: 'COL_9',
    fieldId: 574,
    fieldName: '密度',
    dataType: 'NUMBER',
    tableAliasName: 'uKXdX',
    tableName: 'ODS_Pickup',
    value: ''
  },
  COL_10: {
    field: 'COL_10',
    fieldId: 575,
    fieldName: '折升',
    dataType: 'NUMBER',
    tableAliasName: 'uKXdX',
    tableName: 'ODS_Pickup',
    value: ''
  },
  COL_11: {
    field: 'COL_11',
    fieldId: 576,
    fieldName: '付款单位',
    dataType: 'STRING',
    tableAliasName: 'uKXdX',
    tableName: 'ODS_Pickup',
    value: ''
  },
  COL_12: {
    field: 'COL_12',
    fieldId: 577,
    fieldName: '收款单位',
    dataType: 'STRING',
    tableAliasName: 'uKXdX',
    tableName: 'ODS_Pickup',
    value: ''
  },
  COL_13: {
    field: 'COL_13',
    fieldId: 578,
    fieldName: '提油人',
    dataType: 'STRING',
    tableAliasName: 'uKXdX',
    tableName: 'ODS_Pickup',
    value: ''
  },
  COL_14: {
    field: 'COL_14',
    fieldId: 579,
    fieldName: '车牌号',
    dataType: 'STRING',
    tableAliasName: 'uKXdX',
    tableName: 'ODS_Pickup',
    value: ''
  },
  COL_15: {
    field: 'COL_15',
    fieldId: 580,
    fieldName: '单据照片',
    dataType: 'STRING',
    tableAliasName: 'uKXdX',
    tableName: 'ODS_Pickup',
    value: ''
  },
  COL_16: {
    field: 'COL_16',
    fieldId: 581,
    fieldName: '采购单名称',
    dataType: 'STRING',
    tableAliasName: 'uKXdX',
    tableName: 'ODS_Pickup',
    value: ''
  },
  COL_17: {
    field: 'COL_17',
    fieldId: 582,
    fieldName: '提油人手机号码',
    dataType: 'STRING',
    tableAliasName: 'uKXdX',
    tableName: 'ODS_Pickup',
    value: ''
  },
  COL_18: {
    field: 'COL_18',
    fieldId: 583,
    fieldName: '提交日期',
    dataType: 'DATETIME',
    tableAliasName: 'uKXdX',
    tableName: 'ODS_Pickup',
    value: dayjs().valueOf()
  },
  COL_19: {
    field: 'COL_19',
    fieldId: 584,
    fieldName: '最后修改日期',
    dataType: 'DATETIME',
    tableAliasName: 'uKXdX',
    tableName: 'ODS_Pickup',
    value: dayjs().valueOf()
  },
  COL_20: {
    field: 'COL_20',
    fieldId: 585,
    fieldName: '项目编号',
    dataType: 'STRING',
    tableAliasName: 'uKXdX',
    tableName: 'ODS_Pickup',
    value: ''
  },
  unit_type: {
    field: 'unit_type',
    fieldId: 588,
    fieldName: '单位吨或者升',
    dataType: 'STRING',
    tableAliasName: 'uKXdX',
    tableName: 'ods_pickup',
    value: '吨'
  },
  settlement_type: {
    field: 'settlement_type',
    fieldId: 587,
    fieldName: '结算类型，1已结算，2未结算',
    dataType: 'NUMBER',
    tableAliasName: 'xwZJh',
    tableName: 'ods_pickup',
    value: '0'
  }
})

let id = ''
onLoad((options) => {
  if (options.query) {
    setTimeout(() => {
      const item = JSON.parse(decodeURIComponent(options.query))
      id = item.ID
      Object.values(formData.value).forEach((item2) => {
        item2.value = item[item2.field]
      })
      fileList.value = item.COL_15.map((item) => {
        return {
          name: item.name,
          url: 'https://miniappnew.zhangmushiye.com/api/file/getFileInputStreamById/' + item
        }
      })
    })
  }
})

const formSubmit = () => {
  if (!formData.value.COL_9.value) {
    toast.show('请选择项目名称')
    return
  }
  // 采购单号
  if (!formData.value.COL_4.value) {
    toast.show('请选择采购单号')
    return
  }
  // 提油数量
  if (!formData.value.COL_6.value) {
    toast.show('请输入提油数量')
    return
  }
  // 单位
  if (!formData.value.unit_type.value) {
    toast.show('请选择单位')
    return
  }
  // 单据照片
  if (!formData.value.COL_15.value) {
    toast.show('请上传单据照片')
    return
  }
  let params = {}
  Object.values(formData.value).forEach((item) => {
    let value = item.value
    params[item.fieldId] = value
  })
  params[565] = dayjs(params[565]).valueOf()
  if (id) {
    params[583] = dayjs(params[583]).valueOf()
    params[584] = dayjs().valueOf()
  }
  let val = ''
  params[580].forEach((v) => {
    val += v + ';'
  })
  params[580] = val.substring(0, val.length - 1)
  if (formData.value.COL_9.value < 0.82 || formData.value.COL_9.value >= 0.85) {
    toast.error('提油密度不能是' + formData.value.COL_9.value)
    return
  }
  console.log(formData.value, params)
  params = JSON.stringify(params)
  messageBox
    .confirm({
      title: '提示',
      msg: '确认提交吗？'
    })
    .then(() => {
      toast.loading({ loadingType: 'ring', msg: '提交中' })
      let url = 'https://miniappnew.zhangmushiye.com/visual-api/paas/visualdev/data/Base/v3'
      if (id) {
        url = url + '/primary/6e28f33ce0bb4ac1ca8a41c1d0ed4718/' + id + '/34'
        // PUT 提交
        uni.request({
          url,
          method: 'PUT',
          header: {
            'Blade-Auth': token.value
          },
          data: {
            primaryTable: {
              dbLink: '34',
              id: id,
              oldData: null,
              data: params
            },
            foreignTable: []
          },
          success: (res) => {
            toast.success('提交成功')
            uni.navigateBack()
          },
          fail: (err) => {
            toast.error('提交失败')
          }
        })
      } else {
        url = url + '/6e28f33ce0bb4ac1ca8a41c1d0ed4718'
        uni.request({
          url,
          method: 'POST',
          header: {
            'Blade-Auth': token.value
          },
          data: {
            primaryTable: {
              dbLink: '34',
              id: '',
              oldData: null,
              data: params
            },
            foreignTable: []
          },
          success: (res) => {
            toast.success('提交成功')
            uni.navigateBack()
          },
          fail: (err) => {
            toast.error('提交失败')
          }
        })
      }
    })
    .catch((error) => {
      console.log(error)
    })
}

// 获取gps
// uni.getLocation({
//   type: 'gcj02',
//   success: function (res) {
//     formData.value.COL_13.value = res.longitude
//     formData.value.COL_14.value = res.latitude
//   }
// })
import DemoApi from '@/api/DemoApi'
import { token } from '@/pages/user'

const fileList = ref([])

function handleChange(files) {
  let file = []
  files.fileList.forEach((item) => {
    file.push(item)
  })
  formData.value.COL_15.value = file.map((item) => {
    let res = {}
    try {
      res = JSON.parse(item.response)
    } catch (e) {
      res = item.response
    }
    if (!item.response) {
      res = {
        data: {
          id: item.name
        }
      }
    }
    return res.data.id
  })
  console.log(formData.value.COL_15.value)
}

// 项目列表
const columns = ref([])
columns.value = userInfo.value.xiangmuList
// 单据列表
const kehuList = ref([])
watch(
  () => formData.value.COL_20.value,
  async (val) => {
    await DemoApi.purchase({ xiangmu_id: val }).then((res) => {
      kehuList.value = res.data.map((item) => {
        item.COL_0 = dayjs(item.COL_0).format('YYYY-MM-DD')
        item.label = `${item.label}_${item.COL_0}${item.CGID ? '_' + item.CGID : ''}`
        item.value = item.CGID || item.label
        return item
      })
    })
  }
)
const chooseLicensePlate = () => {
  wx.chooseLicensePlate({
    success: (res) => {
      formData.value.COL_14.value = res.plateNumber
    }
  })
}

watch(
  () => formData.value.COL_4.value,
  async (val) => {
    await DemoApi.purchase({ xiangmu_id: formData.value.COL_20.value }).then((res) => {
      kehuList.value = res.data.map((item) => {
        item.COL_0 = dayjs(item.COL_0).format('YYYY-MM-DD')
        item.label = `${item.label}_${item.COL_0}${item.CGID ? '_' + item.CGID : ''}`
        item.value = item.CGID || item.label
        return item
      })
    })
    const item = kehuList.value.find((item) => item.value == val)
    await uni.request({
      url: 'https://miniappnew.zhangmushiye.com/bi-api/report/dataapi/qiumidu',
      method: 'GET',
      data: { COL_0: formData.value.COL_20.value, COL_4: item.COL_2, COL_5: item.COL_3 },
      header: {
        'content-type': 'application/json',
        Authorization: 'Bearer ' + userInfo.value.token
      },
      success: (res) => {
        if (res.data.data.length > 0) {
          formData.value.COL_9.value = (res.data.data[0].COL_6 * 1).toFixed(2)
        }
        // 密度
      }
    })
  }
)

watch(
  formData.value,
  async (val) => {
    if (val.COL_9.value) {
      await DemoApi.purchase({ xiangmu_id: formData.value.COL_20.value }).then((res) => {
        kehuList.value = res.data.map((item) => {
          item.COL_0 = dayjs(item.COL_0).format('YYYY-MM-DD')
          item.label = `${item.label}_${item.COL_0}${item.CGID ? '_' + item.CGID : ''}`
          item.value = item.CGID || item.label
          return item
        })
      })
      const item = kehuList.value.find((item) => item.value === val.COL_4.value)
      console.log(item)
      // 项目名称
      formData.value.COL_1.value = item.COL_15
      // 油品名称
      formData.value.COL_2.value = item.COL_2
      // 油品型号
      formData.value.COL_3.value = item.COL_3
      // 采购单名称
      formData.value.COL_16.value = item.label
      // 打款数量
      formData.value.COL_5.value = item.COL_4

      // 采购单价
      formData.value.COL_7.value = item.COL_5
      // 采购金额
      formData.value.COL_8.value = item.COL_5 * val.COL_6.value
      // 折升
      formData.value.COL_10.value = ((val.COL_6.value / formData.value.COL_9.value) * 1000).toFixed(3)
      // 付款单位
      formData.value.COL_11.value = item.COL_13
      // 收款单位
      formData.value.COL_12.value = item.COL_12
      // 提油人
      formData.value.COL_13.value = userInfo.value.name
      // 提油人手机号码
      formData.value.COL_17.value = userInfo.value.COL_1
    }
  },
  { deep: true }
)
</script>

<style lang="scss">
.publish {
  background-image: url('https://pic.imgdb.cn/item/65597b6dc458853aef74938b.png');

  .form {
    background: #fff;
    border-radius: 10px;
    padding: 20px;
    margin-top: 20px;
  }
}
</style>
